<?php
/**
 * Created by PhpStorm.
 * User: 我想有个家
 * Date: 2020/4/14
 * Time: 17:28
 */

namespace App\Service;


use App\Log;
use Hyperf\Contract\ConfigInterface;
use OSS\OssClient;

class OssService {
    private $accessKey;
    private $accessSecret;
    private $bucket;
    private $endpoint;

    public function __construct(ConfigInterface $config) {
        $config = $config->get('md.ali');
        $this->accessKey = $config['accessKey'];
        $this->accessSecret = $config['accessSecret'];
        $this->bucket = $config['bucket'];
        $this->endpoint = $config['endpoint'];
    }

    public function saveHeaderImg($headerUrl) {
        $path = "img/" . date('Ymd') . "/" . uuid() . ".png";
        return $this->upload($path, file_get_contents($headerUrl));
    }

    /**
     * 上传文件
     * @param string $path oss保存路径(包含文件名)，不能以/开始
     * @param $content
     * @return string 返回空则上传异常
     */
    public function upload($path, $content) {
        try {
            $ossClient = new OssClient($this->accessKey, $this->accessSecret, $this->endpoint);
            $ossClient->putObject($this->bucket, $path, $content);
        } catch (\Exception $e) {
            Log::get('oss')->error($e->getMessage());
            return '';
        }
        return "/{$path}";
    }

    /**
     * 删除OSS文件
     * @param string $path oss保存路径(包含文件名)，不能以/开始
     */
    public function delete($path) {
        try {
            $ossClient = new OssClient($this->accessKey, $this->accessSecret, $this->endpoint);
            $ossClient->deleteObject($this->bucket, trim($path, '/'));
        } catch (\Exception $e) {
            Log::get('oss')->error($e->getMessage());
        }
    }
}
